#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "../include/ipc.h"
#include "../include/web_ctrl_m0.h"
#include "../include/unicom.h"

//#define NOBLOCK

int init_msg_queue(struct ipc_info *p_ipc_info)
{
	if ((p_ipc_info->mkey = ftok("/app", 'g')) < 0)
	{
		perror("ftok");
		return -1;
	}

	if ((p_ipc_info->msgid = msgget(p_ipc_info->mkey, 0666 | IPC_CREAT)) < 0)
	{
		perror("msgget");
		return -1;
	}

	return 0;
}

/*
 *实现A9从消息队列读取消息，实现网页控制M0上设备
 **/
int web_ctl_m0(int uart_fd, struct ipc_info *p_ipc_info)
{
	int ret;
	struct msg msg_buf;

	memset(&msg_buf, 0, sizeof(struct msg));

	/* 阻塞方式读消息队列 */
	int flag = 0;

#ifdef NOBLOCK
	flag = IPC_NOWAIT;
#endif

	ret = msgrcv(p_ipc_info->msgid, &msg_buf, sizeof(msg_buf) - sizeof(long), 1L, flag);
	fprintf(stderr, "ret: %d\n", ret);
	if (ret == -1)
	{
		perror("msgrcv");
		return -1;
	}

	/* 如果消息队列不为空 */
	puts("write cmd &&&&&&&&&&&&&&&&&&&&&&&&&");
	ret = write(uart_fd, &(msg_buf.text[0]), sizeof(msg_buf.text[0]));
	if (ret != sizeof(msg_buf.text[0]))
	{
		perror("web_ctl_m0 write");
		return -1;
	}

	fprintf(stderr, "ok text: %#x\n", msg_buf.text[0]);
	fprintf(stderr, "ok msgtype: %ld\n", msg_buf.msgtype);
	fprintf(stderr, "ok type: %ld\n", msg_buf.type);

	return 0;
}